IMAGE_NAME=nginx
VERSION=perl
PORT=8080
DIR=/home/app/$IMAGE_NAME/logs

if [ -d "./Dockerfile" ]; then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi

if [ ! -d "$DIR" ]; then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi

echo "remove old container"

EM_RUN=$(docker ps| grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')

if [ -n "$EM_RUN" ]; then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ]; then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $IMAGE_NAME"
fi

echo "run new container"
docker run --name $IMAGE_NAME -d \
-p $PORT:$PORT \
-v /home/app/$IMAGE_NAME/logs:/var/log/nginx \
-v /home/app/$IMAGE_NAME/app:/home/app/nginx/app \
-v /home/app/$IMAGE_NAME/config/nginx.conf:/etc/$IMAGE_NAME/nginx.conf \
--restart=always $IMAGE_NAME:$VERSION